package com.daifeng.gulimall.search.services.Impl;


import com.alibaba.fastjson.JSON;
import com.daifeng.common.to.es.SkuEsModel;
import com.daifeng.gulimall.search.constant.Esconstant;
import com.daifeng.gulimall.search.services.EsprodcutSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class prodcutSaveServiceImpl implements EsprodcutSaveService {

    @Resource(name = "restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * 向es中批量添加商品数据
     * @param esModels
     * @return
     */
    @Override
    public Boolean bulkIndex(List<SkuEsModel> esModels) throws IOException {
        //批量操作的Request
        BulkRequest request = new BulkRequest();
        request.timeout("5m");

        esModels.forEach(System.out::println);

        //批量处理请求
        for (int i = 0; i < esModels.size(); i++) {
            request.add(
                    new IndexRequest(Esconstant.PRODUCT_INDEX)
                            .source(JSON.toJSONString(esModels.get(i)),XContentType.JSON)
            );
        }
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        //response.hasFailures()是否是失败的  true为失败
        if(response.hasFailures()){
           log.info("向es中批量添加商品数据出错了=====>>>>>>>>prodcutSaveServiceImpl中");
        }
        return !response.hasFailures();
    }

}
